<template>
  <Card dis-hover :bordered="false">
    <Form inline v-if="type == 'sucai'">
      <Button
        type="primary"
        @click="handleAdd"
        class="ivu-mb-16"
        v-hasC="{
          name: 'v1-base-tool-category-create',
          flag: 'v1/base/tool-category/create',
        }"
        >新增</Button
      >
    </Form>
    <Form inline v-else>
      <Button
        type="primary"
        @click="handleAdd"
        class="ivu-mb-16"
        v-hasC="{
          name: 'v1-base-common-status-update-common-status',
          flag: 'v1/base/common-status/update-common-status',
        }"
        >新增</Button
      >
    </Form>
    <Table
      :columns="columns"
      :data="list"
      row-key="id"
      :loading="loading"
      :max-height="tableHeigth"
    >
      <template #status_name="{ row }">
        <Badge
          status="success"
          :text="row.status_name"
          v-if="row.status_name === '正常'"
        />
        <Badge status="error" :text="row.status_name" v-else />
      </template>
      <template #action="{ row }">
        <span v-if="type == 'sucai' && row.is_builtin == 1">
          <a
            @click="handleEdit(row)"
            :disabled="true"
            v-hasC="{
              name: 'v1-base-tool-category-update',
              flag: 'v1/base/tool-category/update',
            }"
            >编辑</a
          >
          <Divider
            type="vertical"
            v-hasC="{
              name: 'v1-base-tool-category-update',
              flag: 'v1/base/tool-category/update',
            }"
          />
          <a
            @click="handleDel(row.id)"
            class="del"
            :disabled="true"
            v-hasC="{
              name: 'v1-base-tool-category-delete',
              flag: 'v1/base/tool-category/delete',
            }"
            >删除</a
          >
        </span>
        <span v-else-if="type == 'sucai' && row.status == 1">
          <a
            @click="handleEdit(row)"
            v-hasC="{
              name: 'v1-base-tool-category-update',
              flag: 'v1/base/tool-category/update',
            }"
            >编辑</a
          >
          <Divider
            type="vertical"
            v-hasC="{
              name: 'v1-base-tool-category-update',
              flag: 'v1/base/tool-category/update',
            }"
          />
          <a
            @click="handleDel(row.id)"
            class="del"
            :disabled="true"
            v-hasC="{
              name: 'v1-base-tool-category-delete',
              flag: 'v1/base/tool-category/delete',
            }"
            >删除</a
          >
        </span>
        <span v-else>
          <a
            @click="handleEdit(row)"
            v-hasC="{
              name: 'v1-base-common-status-update-common-status2',
              flag: 'v1/base/common-status/update-common-status',
            }"
            >编辑</a
          >
          <Divider
            type="vertical"
            v-hasC="{
              name: 'v1-base-common-status-update-common-status2',
              flag: 'v1/base/common-status/update-common-status',
            }"
          />
          <a
            @click="handleDel(row.id)"
            class="del"
            v-hasC="{
              name: 'v1-base-common-status-delete-common-status',
              flag: 'v1/base/common-status/delete-common-status',
            }"
            >删除</a
          >
        </span>
      </template>
    </Table>
    <Page
      class="ivu-mt-16"
      :total="total"
      :modelValue="params.current"
      :page-size="params.size"
      :page-size-opts="pageOpts"
      show-total
      show-sizer
      @on-change="changePage"
      @on-page-size-change="changepageSize"
    />
    <Modal
      :mask-closable="false"
      v-model="addModal"
      :title="edit ? '新增' : '编辑'"
      :footer-hide="true"
      :draggable="true"
    >
      <Form ref="create" :model="basicSetInfo" :rules="rules" :label-width="60">
        <FormItem label="名称" prop="name" required>
          <Input
            v-model="basicSetInfo.name"
            placeholder="请输入名称"
            :maxlength="30"
          />
        </FormItem>
        <FormItem label="父级" prop="pid" v-if="type == 'sucai'">
          <Select
            v-model="basicSetInfo.pid"
            :disabled="
              basicSetInfo.children && basicSetInfo.children.length > 0
            "
          >
            <Option
              :value="+item.value"
              v-for="item in pList"
              :key="item.value"
              :disabled="item.value == basicSetInfo.id"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="排序" prop="sort">
          <InputNumber
            v-model="basicSetInfo.sort"
            placeholder="排序"
            :min="0"
          />
        </FormItem>
        <FormItem label="状态" prop="status">
          <Switch v-model="basicSetInfo.status" />
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: right">
        <Button type="default" @click="addModal = false">取消</Button>
        <Button
          type="primary"
          @click="ok"
          style="margin-left: 10px"
          :loading="btnLoading"
          >确定</Button
        >
      </div>
    </Modal>
  </Card>
</template>
<script>
import {
  basicSetList,
  createBasicSet,
  deleteBasicSet,
  toolCategoryList,
  toolCategoryUpdate,
  toolCategoryDel,
  toolCategoryInfo,
} from "@api/basicset.js";
export default {
  name: "content",
  props: ["type", "currentTab"],
  data() {
    return {
      tableHeigth: document.body.clientHeight - 310,
      addModal: false,
      edit: true,
      loading: false,
      btnLoading: false,
      params: { current: 1, size: 10 },
      currentIndex: "",
      total: 0,
      pageOpts: [10, 20, 30, 40],
      columns:
        this.type == "sucai"
          ? [
              {
                key: "name",
                title: "名称",
                tree: true,
              },
              {
                key: "id",
                title: "ID",
              },
              {
                key: "sort",
                title: "排序",
              },
              {
                slot: "status_name",
                title: "状态",
              },
              {
                slot: "action",
                title: "操作",
                width: 110,
                fixed: "right",
              },
            ]
          : [
              {
                key: "id",
                title: "ID",
                width: 80,
                tree: true,
              },
              {
                key: "name",
                title:
                  this.type == "content"
                    ? "分类名称"
                    : this.type == "accounts"
                    ? "类型名称"
                    : "名称",
                minWidth: 125,
              },
              {
                key: "sort",
                title: "排序",
              },
              {
                slot: "status_name",
                title: "状态",
              },
              {
                slot: "action",
                title: "操作",
                width: 110,
                fixed: "right",
              },
            ],
      list: [],
      pList: [],
      basicSetInfo: {
        id: "",
        type: "",
        name: "",
        sort: 100,
        status: true,
        pid: 0,
      },
      rules: {
        name: [{ required: true, message: "请输入名称" }],
      },
    };
  },
  watch: {
    currentTab() {
      this.currentIndex = this.currentTab;
    },
  },
  methods: {
    initData() {
      this.basicSetInfo = {
        id: "",
        type: "",
        name: "",
        sort: 100,
        status: true,
        pid: 0,
      };
    },
    //切换page
    changePage(index) {
      this.params.current = index;
      this.getData(this.currentTab);
    },
    changepageSize(val) {
      this.params.size = val;
      this.getData(this.currentTab);
    },
    handleDel(index) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "是否确认删除此条记录，删除后不可恢复",
        onOk: () => {
          if (this.type == "sucai") {
            toolCategoryDel({ id: index })
              .then(() => {
                this.$Message.success("删除成功");
                this.getData(this.currentTab);
              })
              .catch(() => {});
          } else {
            deleteBasicSet({ id: index, type: this.currentTab })
              .then(() => {
                this.$Message.success("删除成功");
                this.getData(this.currentTab);
              })
              .catch(() => {});
          }
        },
      });
    },
    handleAdd() {
      this.initData();
      this.addModal = true;
      this.edit = true;
      this.$refs.create.resetFields();
      if (this.type == "sucai") {
        toolCategoryInfo({ id: 0 }).then((res) => {
          this.pList = res.condition;
        });
      }
    },
    handleEdit(info) {
      this.addModal = true;
      this.edit = false;
      this.initData();
      this.$refs.create.resetFields();
      if (this.type == "sucai") {
        toolCategoryInfo({ id: info.id }).then((res) => {
          this.pList = res.condition;
          this.basicSetInfo = {
            id: info.id,
            type: this.currentTab,
            name: info.name,
            sort: parseInt(info.sort),
            status: info.status == 1 ? true : false,
            pid: +info.pid,
            children: info.children,
          };
        });
      } else {
        this.basicSetInfo = {
          id: info.id,
          type: this.currentTab,
          name: info.name,
          sort: parseInt(info.sort),
          status: info.status == 1 ? true : false,
          children: info.children,
        };
      }
    },
    changeData(data) {
      data.forEach((item) => {
        item._showChildren = true;
      });
      return data;
    },
    getData(type) {
      this.loading = true;
      const params = {
        pageSize: this.params.size,
        page: this.params.current,
        order_column: this.params.order_column,
        order_sort: this.params.order_sort,
        type: type,
      };
      if (type == "sucai") {
        toolCategoryList(params)
          .then((res) => {
            this.list = this.changeData(res.list);
            this.total = res.total;
            this.loading = false;
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        basicSetList(params)
          .then((res) => {
            this.list = res.list;
            this.total = res.total;
            this.loading = false;
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    addBasicSet() {
      this.btnLoading = true;
      const params = {
        type: this.basicSetInfo.type,
        name: this.basicSetInfo.name,
        sort: this.basicSetInfo.sort,
        status: this.basicSetInfo.status ? 1 : 0,
      };
      if (this.type == "sucai") {
        params.pid = this.basicSetInfo.pid ? this.basicSetInfo.pid : 0;
        if (this.edit) {
          toolCategoryUpdate(params)
            .then((res) => {
              this.$Message.success("添加成功");
              this.addModal = false;
              this.btnLoading = false;
              this.params.current = 1;
              this.getData(this.currentTab);
            })
            .catch(() => {
              this.btnLoading = false;
            });
        } else {
          toolCategoryUpdate(
            Object.assign({}, params, { id: this.basicSetInfo.id })
          )
            .then((res) => {
              this.$Message.success("编辑成功");
              this.addModal = false;
              this.btnLoading = false;
              this.getData(this.currentTab);
            })
            .catch(() => {
              this.btnLoading = false;
            });
        }
      } else {
        if (this.edit) {
          createBasicSet(params)
            .then((res) => {
              this.$Message.success("添加成功");
              this.addModal = false;
              this.btnLoading = false;
              this.params.current = 1;
              this.getData(this.currentTab);
            })
            .catch(() => {
              this.btnLoading = false;
            });
        } else {
          createBasicSet(
            Object.assign({}, params, { id: this.basicSetInfo.id })
          )
            .then((res) => {
              this.$Message.success("编辑成功");
              this.addModal = false;
              this.btnLoading = false;
              this.getData(this.currentTab);
            })
            .catch(() => {
              this.btnLoading = false;
            });
        }
      }
    },
    ok() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          this.addBasicSet();
        } else {
          this.addModal = true;
          // this.$Message.error('填写错误，保存失败！')
          return;
        }
      });
    },
  },
};
</script>
